package com.xand.bt.terminal.util;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;

import com.xand.bt.terminal.main.BitcoinTerminalConfiguration;

public class ConfigurationReader {

	public static BitcoinTerminalConfiguration buildBitcoinTerminalConfiguration(Properties props) {
		
		String connectors = props.getProperty("terminal.connectors");
		List<String> connectorsList = new ArrayList<String>();
		
		StringTokenizer st = new StringTokenizer(connectors, ";");
		while(st.hasMoreTokens()) {
			connectorsList.add(st.nextToken().trim());
		}
		
		
		// read the properties of every connector
		Map<String, Properties> connectorPropertiesMap = new HashMap<String, Properties>();
		
		for(String connector : connectorsList) {
			
			Properties connectorProps = new Properties();
			
			Enumeration<Object> keys = props.keys();
			while(keys.hasMoreElements()) {
				String propName = (String)keys.nextElement();
				String propValue = props.getProperty(propName);
				
				String propNameForConnector = "connector." + connector + ".";
				
				if(propName.startsWith(propNameForConnector)) {
					
					String shortPropName = propName.substring(propNameForConnector.length());
					connectorProps.put(shortPropName, propValue);
					
				}
			}
			
			connectorPropertiesMap.put(connector, connectorProps);
			
		}
		
		BitcoinTerminalConfiguration ret = new BitcoinTerminalConfiguration(connectorsList, connectorPropertiesMap);
		
		return ret;
		
	}
	
}
